package com.example.cp.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.cp.config.HiddenProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletResponse;
import javax.websocket.server.PathParam;
import java.io.IOException;

/**
 * Created by hemin on 2019/8/16.
 */
@Controller
@RequestMapping("/user")
public class LoginController {

    private String prefix = "system/hidden/";

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    HiddenProperties hiddenProperties;

    @GetMapping("/index/{userId}")
    public String index(@PathVariable("userId") String userId, ModelMap modelMap){
        String url = hiddenProperties.getHeaderUrl() + "userInfo/isBind?userId="+userId;
        JSONObject result = restTemplate.getForObject(url, JSONObject.class);
        modelMap.put("msg",result.getString("statusMsg"));
        modelMap.put("data",result.getJSONObject("data").toJSONString());
        return "/index";
    }

    /**
     * 绑定
     */
    @GetMapping("/bind")
    @ResponseBody
    public JSONObject config(@RequestParam("openId")String openId,
                         @RequestParam("name") String name,
                         @RequestParam("id") String id) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        String url = hiddenProperties.getHeaderUrl() + "/userInfo/bind";
        String json = "{userId:\""+openId+"\",name:\""+name+"\",id:\""+id+"\",bindType:0}";
        HttpEntity<String> entity = new HttpEntity<>(json, headers);
        JSONObject forObject = restTemplate.postForObject(url,entity,JSONObject.class);
        return forObject;
    }
    /**
     * 解绑
     */
    @GetMapping("/unbind")
    @ResponseBody
    public JSONObject config1(@RequestParam("openId")String openId,
                             @RequestParam("name") String name,
                             @RequestParam("id") String id) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        String url = hiddenProperties.getHeaderUrl() + "/userInfo/bind";
        String json = "{userId:\""+openId+"\",name:\""+name+"\",id:\""+id+"\",bindType:1}";
        HttpEntity<String> entity = new HttpEntity<>(json, headers);
        JSONObject forObject = restTemplate.postForObject(url,entity,JSONObject.class);
        return forObject;
    }
}
